package com.sdy.dcsb.web.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sdy.common.model.Response;
import com.sdy.common.utils.StringUtil;
import com.sdy.dcsb.biz.model.SUser;
import com.sdy.dcsb.biz.model.SUserJoint;
import com.sdy.dcsb.biz.service.SUserService;
import com.sdy.dcsb.biz.service.UserOperationLogService;
import com.sdy.dcsb.web.controller.inboundservice.util.CopyUtil;
import com.sdy.dcsb.web.controller.inboundservice.util.Md5Util;
import com.sdy.mvc.controller.BaseController;
import com.sdy.mvc.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.*;
import static org.springframework.util.StringUtils.isEmpty;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author fb
 * @since 2019-10-08
 */
@Slf4j
@Controller
@RequestMapping("/SUser")
@Api(tags = "系统用户控制相关接口")
public class SUserController extends BaseController {
    @Autowired
    private SUserService sUserService;
    @Autowired
    private UserOperationLogService userOperationLogService;
    @Autowired
    private FileService fileService;

    private static String key = "6770b5fb0a1c43f0ae3fcc1b89f491cd";

    /**
     * 查询账号信息,分页
     * @param type 查询类别,1:账号 2:姓名 3:电话
     * @param message ,查询值
     * @param page [current, size]
     * @return
     */
    @GetMapping("/select")
    @ResponseBody
    @ApiOperation("查询账号信息,分页")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "type", value = "查询类别,1:账号 2:姓名 3:电话"),
            @ApiImplicitParam(dataType = "String", name = "message", value = "查询值"),
            @ApiImplicitParam(dataType = "String", name = "current", value = "当前页"),
            @ApiImplicitParam(dataType = "String", name = "size", value = "每页数量"),
    })
    public Response select(Integer type, String message, String username, Page<SUser> page) {
        try {
            if(!isEmpty(message)) {
                message = URLDecoder.decode(message,"utf-8");
            }
        }catch(IOException e) {

        }
        QueryWrapper<SUser> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("id");
        if("admin".equals(username)) {

        }else {
            wrapper.eq("username", username == null ? "":username);
        }
        Integer typeN = type == null ? 0:type;
        if(typeN == 3) {
            wrapper.like("p_phone", message == null ? "":message);
        }else if(typeN == 2) {
            wrapper.like("p_name", message == null ? "":message);
        }else if(typeN == 1){
            wrapper.like("username", message == null ? "":message);
        }
        IPage<SUser> result = sUserService.page(page, wrapper);
        List<SUserJoint> sUserJointList = CopyUtil.batchClone(result.getRecords(), SUserJoint.class);
        IPage<SUserJoint> sUserJointIPage = new Page<SUserJoint>(result.getCurrent(), result.getSize(), result.getTotal()).setRecords(sUserJointList);
        return Response.success(sUserJointIPage);
    }

    /**
     * 新增账号
     * @param username 账号
     * @param pName ,联系人名称
     * @param pPhone, 联系人电话
     * @param role, 角色,1:开发者 2:监控者 3:管理员
     * @param password, 密码
     * @param passwordRepeat, 再次输入密码
     * @return
     */
    @GetMapping("/insert")
    @ResponseBody
    @ApiOperation("新增账号")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "username", value = "账号"),
            @ApiImplicitParam(dataType = "String", name = "pName", value = "联系人名称"),
            @ApiImplicitParam(dataType = "String", name = "pPhone", value = "联系人电话"),
            @ApiImplicitParam(dataType = "String", name = "role", value = "角色,1:开发者 2:监控者 3:管理员"),
            @ApiImplicitParam(dataType = "String", name = "password", value = "密码"),
            @ApiImplicitParam(dataType = "String", name = "passwordRepeat", value = "再次输入密码"),
            @ApiImplicitParam(dataType = "String", name = "currentUser", value = "当前登录用户"),
    })
    public Response insert(HttpServletRequest request, String username, String pName, String pPhone, String role, String password,
                           String passwordRepeat, String currentUser) {

        if("admin".equals(currentUser)) {
            if(StringUtil.isNotBlank(username)) {
                try {
                    username = URLDecoder.decode(username,"utf-8");
                    if(!isEmpty(pName)) {
                        pName = URLDecoder.decode(pName,"utf-8");
                    }
                    if(!isEmpty(pPhone)) {
                        pPhone = URLDecoder.decode(pPhone,"utf-8");
                    }
                    if(!isEmpty(role)) {
                        role = URLDecoder.decode(role,"utf-8");
                    }
                    if(!isEmpty(password)) {
                        password = URLDecoder.decode(password,"utf-8");
                    }
                    if(!isEmpty(passwordRepeat)) {
                        passwordRepeat = URLDecoder.decode(passwordRepeat,"utf-8");
                    }
                }catch(IOException e) {
                    return Response.error("URLDecoder失败");
                }
                QueryWrapper<SUser> wrapper = new QueryWrapper<>();
                wrapper.eq("username", username);
                List<SUser> result = sUserService.list(wrapper);
                if(result.size() == 0) {
                    if(!isEmpty(password)) {
                        if(password.equals(passwordRepeat)) {
                            SUser sUser = new SUser();
                            sUser.setUsername(username);
                            sUser.setUpdateTime(new Date());
                            sUser.setPName(pName);
                            sUser.setPPhone(pPhone);
                            sUser.setStatus("1");
                            sUser.setRole(role);
                            // 密码加密
                            password = Md5Util.ecodeByMD5(password+key);
                            sUser.setPassword(password);
                            userOperationLogService.savaUserLog(request, "新建账号：" + username);
                            return Response.success(sUserService.save(sUser));
                        }else {
                            return Response.error("两次输入密码不匹配");
                        }
                    }else {
                        return Response.error("密码不能为空");
                    }
                }else {
                    return Response.error("账号已存在");
                }
            }else {
                return Response.error("新增账号不能为空");
            }
        }else {
            return Response.error("该账户无创建用户权限，请用admin账号新建新用户");
        }
    }

    /**
     * 查询单条信息
     * @param id
     * @return
     */
    @GetMapping("/selectOne")
    @ResponseBody
    @ApiOperation(value = "查询单条信息")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "id"),
    })
    public Response selectOne(Integer id) {
        if(!isEmpty(id)) {
            SUser sUser = sUserService.getById(id);
            SUserJoint sUserJoint = new SUserJoint();
            sUserJoint.setId(sUser.getId());
            sUserJoint.setUsername(sUser.getUsername());
            sUserJoint.setUpdateTime(sUser.getUpdateTime());
            sUserJoint.setPName(sUser.getPName());
            sUserJoint.setPPhone(sUser.getPPhone());
            sUserJoint.setStatus(sUser.getStatus());
            sUserJoint.setRole(sUser.getRole());
            return Response.success(sUserJoint);
        }else {
            return Response.error("请求id不能为空");
        }
    }

    /**
     * 修改账号信息
     * @param username 账号
     * @param pName ,联系人名称
     * @param pPhone, 联系人电话
     * @param status, 状态。1:在用(默认),0:不在用
     * @param role, 角色,1:开发者 2:监控者 3:管理员
     * @return
     */
    @GetMapping("/update")
    @ResponseBody
    @ApiOperation("修改账号信息")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "username", value = "账号"),
            @ApiImplicitParam(dataType = "String", name = "pName", value = "联系人名称"),
            @ApiImplicitParam(dataType = "String", name = "pPhone", value = "联系人电话"),
            @ApiImplicitParam(dataType = "String", name = "status", value = "状态。1:在用(默认),0:不在用"),
            @ApiImplicitParam(dataType = "String", name = "role", value = "角色,1:开发者 2:监控者 3:管理员"),
    })
    public Response update(HttpServletRequest request, String username, String pName, String pPhone, String status, String role) {
        if(!isEmpty(username)) {
            try {
                if(!isEmpty(username)) {
                    username = URLDecoder.decode(username,"utf-8");
                }
                if(!isEmpty(pName)) {
                    pName = URLDecoder.decode(pName,"utf-8");
                }
                if(!isEmpty(pPhone)) {
                    pPhone = URLDecoder.decode(pPhone,"utf-8");
                }
                if(!isEmpty(status)) {
                    status = URLDecoder.decode(status,"utf-8");
                }
                if(!isEmpty(role)) {
                    role = URLDecoder.decode(role,"utf-8");
                }
            }catch(IOException e) {
                return Response.error("URLDecoder失败");
            }
            QueryWrapper<SUser> wrapper = new QueryWrapper<>();
            wrapper.eq("username",username);
            List<SUser> result = sUserService.list(wrapper);
            if(result.size() == 0) {
               return Response.error("请求账号不存在");
            }
            SUser sUser = new SUser();
            Integer i = 0;
            if(!Objects.equals(result.get(0).getPName(), pName)) {
                if(isEmpty(pName)) {
                    sUser.setPName("");
                }else {
                    sUser.setPName(pName);
                }
                i++;
            }
            String nowPPhone = result.get(0).getPPhone();
            if(!Objects.equals(nowPPhone, pPhone)) {
                if(nowPPhone == null && pPhone == "") {

                }else {
                    if(isEmpty(pPhone)) {
                        sUser.setPPhone("");
                    }else {
                        sUser.setPPhone(pPhone);
                    }
                    i++;
                }
            }
            if(!Objects.equals(result.get(0).getStatus(), status)) {
                if(isEmpty(status)) {
                    sUser.setStatus("");
                }else {
                    sUser.setStatus(status);
                }
                i++;
            }
            if(!Objects.equals(result.get(0).getRole(), role)) {
                if(isEmpty(role)) {
                    sUser.setRole("");
                }else {
                    sUser.setRole(role);
                }
                i++;
            }
            if( i >=1 ){
                sUser.setUpdateTime(new Date());
                sUserService.update(sUser, new UpdateWrapper<SUser>().eq("username", username));
                userOperationLogService.savaUserLog(request, "修改账号基本信息成功：" + username);
                return Response.success("修改账号信息成功");
            }else {
                return Response.error("信息无变化");
            }
        }else {
            return Response.error("请求账号不能为空");
        }
    }

    /**
     * 修改密码
     * @param username 账号
     * @param password, 密码
     * @param passwordRepeat, 再次输入密码
     * @return
     */
    @GetMapping("/updatePassword")
    @ResponseBody
    @ApiOperation("修改密码")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "username", value = "账号"),
            @ApiImplicitParam(dataType = "String", name = "password", value = "密码"),
            @ApiImplicitParam(dataType = "String", name = "passwordRepeat", value = "再次输入密码"),
    })
    public Response updatePassword(HttpServletRequest request, String username, String password, String passwordRepeat) {
        if(!isEmpty(username)) {
            try{
                username = URLDecoder.decode(username,"utf-8");
            }catch (Exception e) {
                return Response.error("URLDecoder失败");
            }
            if(!isEmpty(password)) {
                if(password.equals(passwordRepeat)) {
                    SUser sUser = new SUser();
                    password = Md5Util.ecodeByMD5(password+key);
                    sUser.setPassword(password);
                    sUser.setUpdateTime(new Date());
                    sUserService.update(sUser, new UpdateWrapper<SUser>().eq("username", username));
                    userOperationLogService.savaUserLog(request, "修改账号密码成功：" + username);
                    return Response.success("修改密码成功");
                }else {
                    return Response.error("两次输入密码不匹配");
                }
            }else {
                return Response.error("新密码不能为空");
            }
        }else {
            return Response.error("请求账号不能为空");
        }
    }

    /**
     * 删除账号信息
     * @param username 账号
     * @return
     */
    @GetMapping("/delete")
    @ResponseBody
    @ApiOperation("删除账号信息")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "username", value = "账号"),
    })
    public Response delete(HttpServletRequest request, String username) {
        if(!isEmpty(username)){
            try {
                username = URLDecoder.decode(username,"utf-8");
            }catch(IOException e) {

            }
            QueryWrapper<SUser> wrapper = new QueryWrapper<>();
            wrapper.eq("username", username);
            userOperationLogService.savaUserLog(request, "删除账号信息：" + username);
            return Response.success(sUserService.remove(wrapper));
        }else {
            return Response.error("请求账号不能为空");
        }
    }

    /**
     * 账号登陆
     * @return
     */
    @PostMapping("/login")
    @ResponseBody
    @ApiOperation("账号登陆")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "username", value = "账号"),
            @ApiImplicitParam(dataType = "String", name = "password", value = "密码"),
    })
    public Response login(HttpServletRequest request, @RequestBody Map<String, Object> map) {
        String username = "";
        String password = "";
        try{
            username = (String) map.get("username");
            password = (String) map.get("password");
        }catch (Exception e) {
            return Response.error("请求中未传入username或password参数");
        }
        HttpSession session = request.getSession(true);
        QueryWrapper<SUser> wrapper = new QueryWrapper<>();
        // 密码加密 验证
        wrapper.eq("username",username);
        password = Md5Util.ecodeByMD5(password+key);
        wrapper.eq("password",password);
        List<SUser> result = sUserService.list(wrapper);
        if(result.size() > 0 ) {
            if("1".equals(result.get(0).getStatus())){
                SUserJoint sUserJoint = new SUserJoint();
                sUserJoint.setId(result.get(0).getId());
                sUserJoint.setUsername(result.get(0).getUsername());
                sUserJoint.setUpdateTime(result.get(0).getUpdateTime());
                sUserJoint.setPName(result.get(0).getPName());
                sUserJoint.setPPhone(result.get(0).getPPhone());
                sUserJoint.setStatus(result.get(0).getStatus());
                sUserJoint.setRole(result.get(0).getRole());
                String uploadUrl = "";
                try {
                    uploadUrl = fileService.getFsUploadAddr();
                } catch (Exception e) {

                }
                sUserJoint.setUploadUrl(uploadUrl);

                session.setAttribute("user", sUserJoint);
                session.setMaxInactiveInterval(20*60);
                try{
                    userOperationLogService.savaUserLog(request, username, "登录成功");
                }catch (Exception e) {

                }
                return Response.success(sUserJoint);
            }else {
                try{
                    userOperationLogService.savaUserLog(request, username, "登录失败,账户不可用!");
                }catch (Exception e) {

                }
                return Response.error("账户不可用！");
            }
        }else {
            try{
                userOperationLogService.savaUserLog(request, username, "登录失败,用户名或密码错误!");
            }catch (Exception e) {

            }
            return Response.error("用户名或密码错误！");
        }
    }

    /**
     * 验证是否登陆
     * @return
     */
    @GetMapping("/userInfo")
    @ResponseBody
    @ApiOperation("验证是否登陆")
    @ApiImplicitParams({
    })
    public Response userInfo(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session != null && session.getAttribute("user") != null) {
            return Response.success(session.getAttribute("user"));
        }else {
            return Response.error("");
        }
    }

    /**
     * 账号退出
     * @return
     */
    @GetMapping("/loginOut")
    @ResponseBody
    @ApiOperation("账号退出")
    @ApiImplicitParams({
    })
    public Response loginOut(HttpServletRequest request) {
        HttpSession session = request.getSession();
        if(session != null && session.getAttribute("user") != null) {
            SUserJoint sUserJoint = (SUserJoint)session.getAttribute("user");
            session.removeAttribute("user");
            session.invalidate();
        }
        return Response.success("退出成功");
    }

    /**
     * 公司地址信息查询测试接口
     * @return
     */
    @RequestMapping("/checkTest")
    @ResponseBody
    @ApiOperation("公司地址信息查询")
    @ApiImplicitParams({
    })
    public Response checkTest(HttpServletRequest request) {
        JSONObject dataObject = new JSONObject();
        dataObject.put("companyname", "杭州数动云科技有限公司");
        dataObject.put("address", "浙江省杭州市江干区高德置地中心1号楼2202室");
        dataObject.put("telephone", "0571-86081779");
        JSONArray array = new JSONArray();
        array.add(0, dataObject);
        JSONObject object = new JSONObject();
        object.put("code", 200);
        object.put("msg", "查询成功");
        object.put("data", array);
        return Response.success(object);
    }

    /**
     * 婚姻登记历史信息测试接口
     * @return
     */
    @RequestMapping("/marryInfo")
    @ResponseBody
    @ApiOperation("婚姻登记历史信息接口测试")
    @ApiImplicitParams({
    })
    public Response marryInfo(String card) {
        JSONObject dataObject = new JSONObject();
        JSONArray array = new JSONArray();
        JSONObject object = new JSONObject();
        if("341226198312291320".equals(card)){
            dataObject.put("fCardId", "341226198312291320");
            dataObject.put("mCardId", "342401198002230332");
            dataObject.put("fName", "张山");
            dataObject.put("mName", "李思");
            dataObject.put("registrationOrg", "杭州市拱墅区民政局婚姻登记处");
            dataObject.put("registrationDate", "2017-02-15");
            dataObject.put("businessType", "结婚登记");
            dataObject.put("tong_time", "2018-08-21 22:12:35");
            array.add(0, dataObject);
            object.put("code", 200);
            object.put("msg", "查询成功");
            object.put("data", array);
        }else {
            array.add(0, dataObject);
            object.put("code", 500);
            object.put("msg", "查询无数据");
            object.put("data", array);
        }

        return Response.success(object);
    }

    /**
     * 浙江杭州公安机动车基本信息查询测试接口
     * @return
     */
    @RequestMapping("/gonganjdcjbxx")
    @ResponseBody
    @ApiOperation("浙江杭州公安机动车基本信息查询")
    @ApiImplicitParams({
    })
    public Response gonganjdcjbxx(String card) {
        JSONObject dataObject = new JSONObject();
        JSONArray array = new JSONArray();
        JSONObject object = new JSONObject();
        if("341226198312291320".equals(card)){
            dataObject.put("card", "341226198312291320");
            dataObject.put("name", "张山");
            dataObject.put("tele_nbr", "13605819000");
            dataObject.put("zsxxdz", "浙江杭州萧山区XXXXX号");
            dataObject.put("lice_type", "小型汽车");
            dataObject.put("use_type", "非营运");
            dataObject.put("frst_rgstrn", "2012-05-28 16:19:47");
            dataObject.put("car_brand", "丰田牌");
            dataObject.put("fzrq", "2012-05-28 16:24:24");
            dataObject.put("lice_cd", "A193FW");
            dataObject.put("card_name", "居民身份证");
            array.add(0, dataObject);
            object.put("code", 200);
            object.put("msg", "查询成功");
            object.put("data", array);
        }else {
            array.add(0, dataObject);
            object.put("code", 500);
            object.put("msg", "查询无数据");
            object.put("data", array);
        }
        return Response.success(object);
    }

}
